package leetcode.code1764;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public boolean canChoose(int[][] groups, int[] nums) {
		int n = groups.length, size = nums.length;
		int g = 0, p = -1;
		while (g < n && p < size) {
			int[] group = groups[g];
			int len = group.length, sum = 0;
			for (int j = 0; j < len; j++) {
				sum += group[j];
			}
			p = find(nums, p + 1, group[0], group[len - 1], len, sum, group);
			g++;
		}
		return p < size;
	}

	private int find(int[] nums, int start, int first, int last, int len, int total, int[] group) {
		int sum = 0;
		for (int i = start, l = start; i < nums.length; i++) {
			int cur = nums[i];
			sum += cur;
			if (l + len - 1 == i) {
				if (nums[l] == first && cur == last && sum == total) {
					if (this.same(nums, l, len, group)) {
						return i;
					}
				}
				sum -= nums[l++];
			}

		}
		return nums.length;
	}

	private boolean same(int[] nums, int start, int len, int[] group) {
		for (int i = start, j = 0; i < start + len; i++, j++) {
			if (nums[i] != group[j]) {
				return false;
			}
		}
		return true;
	}

	@Override
	public void debug4() {
		H.compare(true, this.canChoose(H.str2array1("[[1,-1,-1],[3,-2,0]]"), H.str2array3("[1,-1,0,1,-1,-1,3,-2,0]")));
		H.compare(false, this.canChoose(H.str2array1("[[10,-2],[1,2,3,4]]"), H.str2array3("[1,2,3,4,10,-2]")));
		H.compare(false, this.canChoose(H.str2array1("[[1,2,3],[3,4]]"), H.str2array3("[7,7,1,2,3,4,7,7]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
